#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
文件格式转换工具
基于PyQt6开发的多格式文件转换应用程序
"""

import sys
import os
from pathlib import Path
from datetime import datetime
from PyQt6.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
    QLabel, QPushButton, QFileDialog, QComboBox, QTextEdit,
    QProgressBar, QMessageBox, QGroupBox, QGridLayout, QSpinBox,
    QRadioButton, QListWidget, QListWidgetItem, QCheckBox
)
from PyQt6.QtCore import Qt, QThread, pyqtSignal, QTimer
from PyQt6.QtGui import QFont, QIcon, QColor

from converter import FileConverter


class ConversionThread(QThread):
    """文件转换线程"""
    progress_updated = pyqtSignal(int)
    conversion_finished = pyqtSignal(bool, str)
    
    def __init__(self, input_file, output_file, conversion_type, conversion_params=None):
        super().__init__()
        self.input_file = input_file
        self.output_file = output_file
        self.conversion_type = conversion_type
        self.conversion_params = conversion_params or {}
        self.converter = FileConverter()
    
    def run(self):
        try:
            # 模拟进度更新
            for i in range(0, 101, 10):
                self.progress_updated.emit(i)
                self.msleep(100)
            
            # 执行转换
            success = self.converter.convert_file(
                self.input_file, 
                self.output_file, 
                self.conversion_type,
                self.conversion_params
            )
            
            if success:
                self.conversion_finished.emit(True, "转换成功！")
            else:
                self.conversion_finished.emit(False, "转换失败，请检查文件格式和路径。")
                
        except Exception as e:
            self.conversion_finished.emit(False, f"转换过程中出现错误：{str(e)}")


class BatchConversionThread(QThread):
    """批量文件转换线程"""
    progress_updated = pyqtSignal(int)
    file_progress_updated = pyqtSignal(str, int)  # 文件名, 进度
    conversion_finished = pyqtSignal(bool, str, dict)  # 成功, 消息, 结果统计
    current_file_changed = pyqtSignal(str)  # 当前处理的文件
    
    def __init__(self, file_list, output_dir, conversion_type, conversion_params=None):
        super().__init__()
        self.file_list = file_list
        self.output_dir = output_dir
        self.conversion_type = conversion_type
        self.conversion_params = conversion_params or {}
        self.converter = FileConverter()
        self.is_cancelled = False
    
    def cancel(self):
        """取消批量转换"""
        self.is_cancelled = True
    
    def run(self):
        try:
            total_files = len(self.file_list)
            success_count = 0
            failed_count = 0
            failed_files = []
            
            for i, input_file in enumerate(self.file_list):
                if self.is_cancelled:
                    break
                
                # 更新当前处理的文件
                file_name = Path(input_file).name
                self.current_file_changed.emit(file_name)
                
                # 生成输出文件路径
                output_file = self._generate_output_path(input_file)
                
                try:
                    # 执行单个文件转换
                    success = self.converter.convert_file(
                        input_file,
                        output_file,
                        self.conversion_type,
                        self.conversion_params
                    )
                    
                    if success:
                        success_count += 1
                        self.file_progress_updated.emit(file_name, 100)
                    else:
                        failed_count += 1
                        failed_files.append(file_name)
                        self.file_progress_updated.emit(file_name, -1)  # -1表示失败
                        
                except Exception as e:
                    failed_count += 1
                    failed_files.append(f"{file_name}: {str(e)}")
                    self.file_progress_updated.emit(file_name, -1)
                
                # 更新总体进度
                overall_progress = int((i + 1) / total_files * 100)
                self.progress_updated.emit(overall_progress)
                
                # 短暂休眠，避免界面卡顿
                self.msleep(50)
            
            # 生成结果统计
            result_stats = {
                'total': total_files,
                'success': success_count,
                'failed': failed_count,
                'failed_files': failed_files
            }
            
            if self.is_cancelled:
                self.conversion_finished.emit(False, "批量转换已取消", result_stats)
            elif failed_count == 0:
                self.conversion_finished.emit(True, f"批量转换完成！成功转换 {success_count} 个文件", result_stats)
            else:
                self.conversion_finished.emit(True, f"批量转换完成！成功 {success_count} 个，失败 {failed_count} 个", result_stats)
                
        except Exception as e:
            result_stats = {'total': 0, 'success': 0, 'failed': 0, 'failed_files': []}
            self.conversion_finished.emit(False, f"批量转换过程中出现错误：{str(e)}", result_stats)
    
    def _generate_output_path(self, input_file):
        """生成输出文件路径"""
        input_path = Path(input_file)
        base_name = input_path.stem
        
        # 获取输出扩展名
        output_extensions = {
            "DOC/DOCX → PDF": ".pdf",
            "DOC/DOCX → ODT": ".odt",
            "XLS/XLSX → PDF": ".pdf",
            "XLS/XLSX → ODS": ".ods",
            "PPT/PPTX → PDF": ".pdf",
            "PPT/PPTX → ODP": ".odp",
            "PDF → TXT": ".txt",
            "RTF → DOCX": ".docx",
            "RTF → TXT": ".txt",
            "EPUB → MOBI": ".mobi",
            "EPUB → PDF": ".pdf",
            "MOBI → EPUB": ".epub",
            "MOBI → PDF": ".pdf",
            "AZW3 → EPUB": ".epub",
            "HTML → PDF": ".pdf",
            "Markdown → HTML": ".html",
            "Markdown → DOCX": ".docx",
            "Markdown → PDF": ".pdf",
            "JPG/JPEG → PNG": ".png",
            "JPG/JPEG → WEBP": ".webp",
            "PNG → JPG": ".jpg",
            "PNG → WEBP": ".webp",
            "WEBP → PNG": ".png",
            "WEBP → JPG": ".jpg",
            "GIF → PNG": ".png",
            "GIF → WEBP": ".webp",
            "BMP → PNG": ".png",
            "BMP → JPG": ".jpg",
            "TIFF → PNG": ".png",
            "TIFF → JPG": ".jpg",
            "RAW → JPG": ".jpg",
            "RAW → PNG": ".png",
            "SVG → PNG": ".png",
            "HEIC → JPG": ".jpg",
            "MP3 → WAV": ".wav",
            "MP3 → FLAC": ".flac",
            "WAV → MP3": ".mp3",
            "WAV → FLAC": ".flac",
            "FLAC → MP3": ".mp3",
            "FLAC → WAV": ".wav",
            "ALAC → MP3": ".mp3",
            "AIFF → MP3": ".mp3",
            "AAC → MP3": ".mp3",
            "MP4 → AVI": ".avi",
            "MP4 → MKV": ".mkv",
            "MP4 → MOV": ".mov",
            "MP4 → WebM": ".webm",
            "AVI → MP4": ".mp4",
            "MKV → MP4": ".mp4",
            "MOV → MP4": ".mp4",
            "WebM → MP4": ".mp4",
            "GIF → MP4": ".mp4",
            "GIF → WebM": ".webm",
            "4K → 1080p": ".mp4",
            "1080p → 4K": ".mp4"
        }
        
        output_ext = output_extensions.get(self.conversion_type, ".out")
        
        # 生成时间戳
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        
        # 生成输出文件名
        conversion_short = self.conversion_type.split(" → ")[1].replace("/", "_")
        output_filename = f"{base_name}_{conversion_short}_{timestamp}{output_ext}"
        
        return str(Path(self.output_dir) / output_filename)


class FileFormatConverter(QMainWindow):
    """主窗口类"""
    
    def __init__(self):
        super().__init__()
        self.input_file = ""
        self.output_file = ""
        self.conversion_thread = None
        self.all_conversion_types = []
        self.setup_format_mappings()
        self.init_ui()
        
    def setup_format_mappings(self):
        """设置文件格式映射"""
        # 定义所有转换类型
        self.all_conversion_types = [
            # 文档转换
            "DOC/DOCX → PDF",
            "DOC/DOCX → ODT",
            "XLS/XLSX → PDF",
            "XLS/XLSX → ODS",
            "PPT/PPTX → PDF",
            "PPT/PPTX → ODP",
            "PDF → TXT",
            "RTF → DOCX",
            "RTF → TXT",
            "EPUB → MOBI",
            "EPUB → PDF",
            "MOBI → EPUB",
            "MOBI → PDF",
            "AZW3 → EPUB",
            "HTML → PDF",
            "Markdown → HTML",
            "Markdown → DOCX",
            "Markdown → PDF",
            # 图像转换
            "JPG/JPEG → PNG",
            "JPG/JPEG → WEBP",
            "JPG/JPEG → SVG",
            "PNG → JPG/JPEG",
            "PNG → WEBP",
            "PNG → SVG",
            "WEBP → JPG/JPEG",
            "WEBP → PNG",
            "GIF → PNG",
            "GIF → WEBP",
            "BMP → JPG/JPEG",
            "BMP → PNG",
            "TIFF → JPG/JPEG",
            "TIFF → PNG",
            "RAW → JPG/JPEG",
            "RAW → PNG",
            "RAW → TIFF",
            "RAW → DNG",
            "SVG → PDF",
            "SVG → PNG",
            "SVG → JPG/JPEG",
            "PDF → JPG/JPEG",
            "PDF → PNG",
            "HEIC → JPG/JPEG",
            "HEIC → PNG",
            # 音频转换
            "MP3 → WAV",
            "WAV → MP3",
            "MP3 → FLAC",
            "FLAC → MP3",
            "FLAC → ALAC",
            "ALAC → FLAC",
            "WAV → AIFF",
            "AIFF → WAV",
            "AAC → MP3",
            "MP3 → AAC",
            "MP4 → MP3",
            "MKV → MP3",
            "AVI → MP3",
            "MP4 → WAV",
            "MKV → WAV",
            "AVI → WAV",
            "MP4 → FLAC",
            "MKV → FLAC",
            "AVI → FLAC",
            # 视频转换
            "MP4 → MKV",
            "MKV → MP4",
            "MP4 → MOV",
            "MOV → MP4",
            "AVI → MP4",
            "AVI → MKV",
            "H.264 → H.265",
            "H.265 → H.264",
            "VP9 → H.264",
            "AV1 → H.264",
            "AV1 → H.265",
            "视频 → GIF",
            "GIF → MP4",
            "GIF → WebM",
            "4K → 1080p",
            "1080p → 4K"
        ]
        
        # 文件扩展名到转换选项的映射
        self.format_mappings = {
            # 文档格式
            '.doc': ["DOC/DOCX → PDF", "DOC/DOCX → ODT"],
            '.docx': ["DOC/DOCX → PDF", "DOC/DOCX → ODT"],
            '.xls': ["XLS/XLSX → PDF", "XLS/XLSX → ODS"],
            '.xlsx': ["XLS/XLSX → PDF", "XLS/XLSX → ODS"],
            '.ppt': ["PPT/PPTX → PDF", "PPT/PPTX → ODP"],
            '.pptx': ["PPT/PPTX → PDF", "PPT/PPTX → ODP"],
            '.pdf': ["PDF → TXT", "PDF → JPG/JPEG", "PDF → PNG"],
            '.rtf': ["RTF → DOCX", "RTF → TXT"],
            '.epub': ["EPUB → MOBI", "EPUB → PDF"],
            '.mobi': ["MOBI → EPUB", "MOBI → PDF"],
            '.azw3': ["AZW3 → EPUB"],
            '.html': ["HTML → PDF"],
            '.md': ["Markdown → HTML", "Markdown → DOCX", "Markdown → PDF"],
            # 图像格式
            '.jpg': ["JPG/JPEG → PNG", "JPG/JPEG → WEBP", "JPG/JPEG → SVG"],
            '.jpeg': ["JPG/JPEG → PNG", "JPG/JPEG → WEBP", "JPG/JPEG → SVG"],
            '.png': ["PNG → JPG/JPEG", "PNG → WEBP", "PNG → SVG"],
            '.webp': ["WEBP → JPG/JPEG", "WEBP → PNG"],
            '.gif': ["GIF → PNG", "GIF → WEBP"],
            '.bmp': ["BMP → JPG/JPEG", "BMP → PNG"],
            '.tiff': ["TIFF → JPG/JPEG", "TIFF → PNG"],
            '.tif': ["TIFF → JPG/JPEG", "TIFF → PNG"],
            '.raw': ["RAW → JPG/JPEG", "RAW → PNG", "RAW → TIFF", "RAW → DNG"],
            '.cr2': ["RAW → JPG/JPEG", "RAW → PNG", "RAW → TIFF", "RAW → DNG"],
            '.nef': ["RAW → JPG/JPEG", "RAW → PNG", "RAW → TIFF", "RAW → DNG"],
            '.arw': ["RAW → JPG/JPEG", "RAW → PNG", "RAW → TIFF", "RAW → DNG"],
            '.dng': ["RAW → JPG/JPEG", "RAW → PNG", "RAW → TIFF"],
            '.svg': ["SVG → PDF", "SVG → PNG", "SVG → JPG/JPEG"],
            '.heic': ["HEIC → JPG/JPEG", "HEIC → PNG"],
            # 音频格式
            '.mp3': ["MP3 → WAV", "MP3 → FLAC", "MP3 → AAC"],
            '.wav': ["WAV → MP3", "WAV → AIFF"],
            '.flac': ["FLAC → MP3", "FLAC → ALAC"],
            '.alac': ["ALAC → FLAC"],
            '.m4a': ["ALAC → FLAC"],
            '.aiff': ["AIFF → WAV"],
            '.aac': ["AAC → MP3"],
            # 视频格式（提取音频和视频转换）
        '.mp4': ["MP4 → MP3", "MP4 → WAV", "MP4 → FLAC", "MP4 → MKV", "MP4 → MOV", "视频 → GIF", "4K → 1080p", "1080p → 4K"],
         '.mkv': ["MKV → MP3", "MKV → WAV", "MKV → FLAC", "MKV → MP4", "视频 → GIF", "4K → 1080p", "1080p → 4K"],
         '.avi': ["AVI → MP3", "AVI → WAV", "AVI → FLAC", "AVI → MP4", "AVI → MKV", "视频 → GIF", "4K → 1080p", "1080p → 4K"],
         '.mov': ["MOV → MP4", "视频 → GIF", "4K → 1080p", "1080p → 4K"],
         '.gif': ["GIF → MP4", "GIF → WebM"],
          '.webm': ["视频 → GIF", "4K → 1080p", "1080p → 4K"],
         # 编解码器转换（需要通过文件扩展名识别）
         '.h264': ["H.264 → H.265"],
         '.h265': ["H.265 → H.264"],
         '.hevc': ["H.265 → H.264"],
         '.vp9': ["VP9 → H.264"],
         '.av1': ["AV1 → H.264", "AV1 → H.265"]
        }
        
        # 转换类型到输出扩展名的映射
        self.output_extensions = {
            # 文档转换
            "DOC/DOCX → PDF": ".pdf",
            "DOC/DOCX → ODT": ".odt",
            "XLS/XLSX → PDF": ".pdf",
            "XLS/XLSX → ODS": ".ods",
            "PPT/PPTX → PDF": ".pdf",
            "PPT/PPTX → ODP": ".odp",
            "PDF → TXT": ".txt",
            "RTF → DOCX": ".docx",
            "RTF → TXT": ".txt",
            "EPUB → MOBI": ".mobi",
            "EPUB → PDF": ".pdf",
            "MOBI → EPUB": ".epub",
            "MOBI → PDF": ".pdf",
            "AZW3 → EPUB": ".epub",
            "HTML → PDF": ".pdf",
            "Markdown → HTML": ".html",
            "Markdown → DOCX": ".docx",
            "Markdown → PDF": ".pdf",
            # 图像转换
            "JPG/JPEG → PNG": ".png",
            "JPG/JPEG → WEBP": ".webp",
            "JPG/JPEG → SVG": ".svg",
            "PNG → JPG/JPEG": ".jpg",
            "PNG → WEBP": ".webp",
            "PNG → SVG": ".svg",
            "WEBP → JPG/JPEG": ".jpg",
            "WEBP → PNG": ".png",
            "GIF → PNG": ".png",
            "GIF → WEBP": ".webp",
            "BMP → JPG/JPEG": ".jpg",
            "BMP → PNG": ".png",
            "TIFF → JPG/JPEG": ".jpg",
            "TIFF → PNG": ".png",
            "RAW → JPG/JPEG": ".jpg",
            "RAW → PNG": ".png",
            "RAW → TIFF": ".tiff",
            "RAW → DNG": ".dng",
            "SVG → PDF": ".pdf",
            "SVG → PNG": ".png",
            "SVG → JPG/JPEG": ".jpg",
            "PDF → JPG/JPEG": ".jpg",
            "PDF → PNG": ".png",
            "HEIC → JPG/JPEG": ".jpg",
            "HEIC → PNG": ".png",
            # 音频转换
            "MP3 → WAV": ".wav",
            "WAV → MP3": ".mp3",
            "MP3 → FLAC": ".flac",
            "FLAC → MP3": ".mp3",
            "FLAC → ALAC": ".m4a",
            "ALAC → FLAC": ".flac",
            "WAV → AIFF": ".aiff",
            "AIFF → WAV": ".wav",
            "AAC → MP3": ".mp3",
            "MP3 → AAC": ".aac",
            "MP4 → MP3": ".mp3",
            "MKV → MP3": ".mp3",
            "AVI → MP3": ".mp3",
            "MP4 → WAV": ".wav",
            "MKV → WAV": ".wav",
            "AVI → WAV": ".wav",
            "MP4 → FLAC": ".flac",
            "MKV → FLAC": ".flac",
            "AVI → FLAC": ".flac",
            # 视频转换输出扩展名
            "MP4 → MKV": ".mkv",
            "MKV → MP4": ".mp4",
            "MP4 → MOV": ".mov",
            "MOV → MP4": ".mp4",
            "AVI → MP4": ".mp4",
            "AVI → MKV": ".mkv",
            "H.264 → H.265": ".mp4",
            "H.265 → H.264": ".mp4",
            "VP9 → H.264": ".mp4",
            "AV1 → H.264": ".mp4",
            "AV1 → H.265": ".mp4",
            "视频 → GIF": ".gif",
            "GIF → MP4": ".mp4",
            "GIF → WebM": ".webm",
            "4K → 1080p": ".mp4",
            "1080p → 4K": ".mp4"
        }
        
    def init_ui(self):
        """初始化用户界面"""
        self.setWindowTitle("文件格式转换工具")
        self.setGeometry(100, 100, 800, 600)
        
        # 创建中央窗口部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 主布局
        main_layout = QVBoxLayout(central_widget)
        
        # 标题
        title_label = QLabel("文件格式转换工具")
        title_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        title_font = QFont()
        title_font.setPointSize(16)
        title_font.setBold(True)
        title_label.setFont(title_font)
        main_layout.addWidget(title_label)
        
        # 副标题
        subtitle_label = QLabel("支持文档、图像、音频、视频等多种格式互转")
        subtitle_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        subtitle_font = QFont()
        subtitle_font.setPointSize(10)
        subtitle_label.setFont(subtitle_font)
        subtitle_label.setStyleSheet("color: #666666; margin-bottom: 10px;")
        main_layout.addWidget(subtitle_label)
        
        # 转换模式选择
        mode_group = QGroupBox("转换模式")
        mode_layout = QHBoxLayout(mode_group)
        
        self.single_mode_radio = QRadioButton("单文件转换")
        self.single_mode_radio.setChecked(True)
        self.single_mode_radio.toggled.connect(self.on_mode_changed)
        mode_layout.addWidget(self.single_mode_radio)
        
        self.batch_mode_radio = QRadioButton("批量转换")
        self.batch_mode_radio.toggled.connect(self.on_mode_changed)
        mode_layout.addWidget(self.batch_mode_radio)
        
        mode_layout.addStretch()
        main_layout.addWidget(mode_group)
        
        # 文件选择区域
        file_group = QGroupBox("文件选择")
        file_layout = QGridLayout(file_group)
        
        # 单文件模式控件
        self.single_file_widget = QWidget()
        single_file_layout = QGridLayout(self.single_file_widget)
        single_file_layout.setContentsMargins(0, 0, 0, 0)
        
        # 输入文件
        single_file_layout.addWidget(QLabel("输入文件:"), 0, 0)
        self.input_file_label = QLabel("未选择文件")
        self.input_file_label.setStyleSheet("QLabel { border: 1px solid gray; padding: 5px; }")
        single_file_layout.addWidget(self.input_file_label, 0, 1)
        
        self.select_input_btn = QPushButton("选择输入文件")
        self.select_input_btn.clicked.connect(self.select_input_file)
        single_file_layout.addWidget(self.select_input_btn, 0, 2)
        
        # 预览编辑按钮
        self.preview_btn = QPushButton("预览编辑")
        self.preview_btn.clicked.connect(self.open_preview_editor)
        self.preview_btn.setEnabled(False)
        self.preview_btn.setToolTip("预览和编辑视频/音频文件")
        single_file_layout.addWidget(self.preview_btn, 0, 3)
        
        # 输出文件
        single_file_layout.addWidget(QLabel("输出文件:"), 1, 0)
        self.output_file_label = QLabel("未设置输出路径")
        self.output_file_label.setStyleSheet("QLabel { border: 1px solid gray; padding: 5px; }")
        single_file_layout.addWidget(self.output_file_label, 1, 1)
        
        self.select_output_btn = QPushButton("选择输出目录")
        self.select_output_btn.clicked.connect(self.select_output_file)
        single_file_layout.addWidget(self.select_output_btn, 1, 2)
        
        file_layout.addWidget(self.single_file_widget, 0, 0, 1, 4)
        
        # 批量转换模式控件
        self.batch_file_widget = QWidget()
        batch_file_layout = QGridLayout(self.batch_file_widget)
        batch_file_layout.setContentsMargins(0, 0, 0, 0)
        
        # 批量文件选择
        batch_file_layout.addWidget(QLabel("输入文件:"), 0, 0)
        self.batch_files_label = QLabel("未选择文件")
        self.batch_files_label.setStyleSheet("QLabel { border: 1px solid gray; padding: 5px; }")
        batch_file_layout.addWidget(self.batch_files_label, 0, 1)
        
        self.select_batch_btn = QPushButton("选择多个文件")
        self.select_batch_btn.clicked.connect(self.select_batch_files)
        batch_file_layout.addWidget(self.select_batch_btn, 0, 2)
        
        self.clear_batch_btn = QPushButton("清空列表")
        self.clear_batch_btn.clicked.connect(self.clear_batch_files)
        batch_file_layout.addWidget(self.clear_batch_btn, 0, 3)
        
        # 输出目录
        batch_file_layout.addWidget(QLabel("输出目录:"), 1, 0)
        self.batch_output_label = QLabel("未设置输出目录")
        self.batch_output_label.setStyleSheet("QLabel { border: 1px solid gray; padding: 5px; }")
        batch_file_layout.addWidget(self.batch_output_label, 1, 1)
        
        self.select_batch_output_btn = QPushButton("选择输出目录")
        self.select_batch_output_btn.clicked.connect(self.select_batch_output_dir)
        batch_file_layout.addWidget(self.select_batch_output_btn, 1, 2)
        
        # 文件列表
        batch_file_layout.addWidget(QLabel("文件列表:"), 2, 0)
        self.batch_files_list = QListWidget()
        self.batch_files_list.setMaximumHeight(100)
        batch_file_layout.addWidget(self.batch_files_list, 2, 1, 1, 3)
        
        self.batch_file_widget.setVisible(False)
        file_layout.addWidget(self.batch_file_widget, 1, 0, 1, 4)
        
        main_layout.addWidget(file_group)
        
        # 初始化批量文件列表
        self.batch_file_list = []
        
        # 转换类型选择
        conversion_group = QGroupBox("转换类型")
        conversion_layout = QVBoxLayout(conversion_group)
        
        self.conversion_combo = QComboBox()
        self.setup_conversion_types()
        conversion_layout.addWidget(self.conversion_combo)
        
        main_layout.addWidget(conversion_group)
        
        # GIF选项组（初始隐藏）
        self.gif_options_group = QGroupBox("GIF动图选项")
        gif_options_layout = QVBoxLayout(self.gif_options_group)
        
        # 帧选择模式
        frame_mode_layout = QHBoxLayout()
        frame_mode_layout.addWidget(QLabel("帧选择模式:"))
        
        self.frame_mode_combo = QComboBox()
        self.frame_mode_combo.addItems(["提取单帧", "提取所有帧", "保持动画"])
        self.frame_mode_combo.currentTextChanged.connect(self.on_frame_mode_changed)
        frame_mode_layout.addWidget(self.frame_mode_combo)
        frame_mode_layout.addStretch()
        gif_options_layout.addLayout(frame_mode_layout)
        
        # 单帧选择控件
        self.single_frame_widget = QWidget()
        single_frame_layout = QHBoxLayout(self.single_frame_widget)
        single_frame_layout.setContentsMargins(0, 0, 0, 0)
        
        single_frame_layout.addWidget(QLabel("选择帧:"))
        self.frame_spinbox = QSpinBox()
        self.frame_spinbox.setMinimum(0)
        self.frame_spinbox.setMaximum(999)
        self.frame_spinbox.setValue(0)
        single_frame_layout.addWidget(self.frame_spinbox)
        
        self.frame_info_btn = QPushButton("获取帧信息")
        self.frame_info_btn.clicked.connect(self.get_gif_frame_info)
        single_frame_layout.addWidget(self.frame_info_btn)
        single_frame_layout.addStretch()
        
        gif_options_layout.addWidget(self.single_frame_widget)
        
        # 帧信息显示
        self.frame_info_label = QLabel("请先选择GIF文件并点击'获取帧信息'")
        self.frame_info_label.setStyleSheet("color: #666666; font-size: 10px;")
        gif_options_layout.addWidget(self.frame_info_label)
        
        self.gif_options_group.setVisible(False)
        main_layout.addWidget(self.gif_options_group)
        
        # 连接信号（在所有控件创建完成后）
        self.conversion_combo.currentTextChanged.connect(self.on_conversion_type_changed)
        
        # 转换按钮区域
        button_layout = QHBoxLayout()
        
        self.convert_btn = QPushButton("开始转换")
        self.convert_btn.setEnabled(False)
        self.convert_btn.clicked.connect(self.start_conversion)
        button_layout.addWidget(self.convert_btn)
        
        self.cancel_btn = QPushButton("取消转换")
        self.cancel_btn.setEnabled(False)
        self.cancel_btn.clicked.connect(self.cancel_conversion)
        button_layout.addWidget(self.cancel_btn)
        
        button_layout.addStretch()
        main_layout.addLayout(button_layout)
        
        # 进度条区域
        progress_group = QGroupBox("转换进度")
        progress_layout = QVBoxLayout(progress_group)
        
        # 总体进度
        self.progress_bar = QProgressBar()
        self.progress_bar.setVisible(False)
        progress_layout.addWidget(self.progress_bar)
        
        # 当前文件信息（批量转换时显示）
        self.current_file_label = QLabel("")
        self.current_file_label.setVisible(False)
        self.current_file_label.setStyleSheet("color: #666666; font-size: 10px;")
        progress_layout.addWidget(self.current_file_label)
        
        # 批量转换进度列表
        self.batch_progress_list = QListWidget()
        self.batch_progress_list.setMaximumHeight(120)
        self.batch_progress_list.setVisible(False)
        progress_layout.addWidget(self.batch_progress_list)
        
        progress_group.setVisible(False)
        main_layout.addWidget(progress_group)
        
        # 存储进度组件的引用
        self.progress_group = progress_group
        
        # 日志区域
        log_group = QGroupBox("转换日志")
        log_layout = QVBoxLayout(log_group)
        
        self.log_text = QTextEdit()
        self.log_text.setMaximumHeight(150)
        self.log_text.setReadOnly(True)
        log_layout.addWidget(self.log_text)
        
        main_layout.addWidget(log_group)
        
        # 状态栏
        self.statusBar().showMessage("就绪")
        
        # 初始化转换线程
        self.conversion_thread = None
        self.batch_conversion_thread = None
        
    def setup_conversion_types(self):
        """设置转换类型选项（初始显示所有选项）"""
        self.conversion_combo.addItems(self.all_conversion_types)
        
    def update_conversion_options(self, input_file_path):
        """根据输入文件格式更新转换选项"""
        if not input_file_path:
            return
            
        # 获取文件扩展名
        file_ext = Path(input_file_path).suffix.lower()
        
        # 清空当前选项
        self.conversion_combo.clear()
        
        # 根据文件格式添加相应的转换选项
        if file_ext in self.format_mappings:
            available_conversions = self.format_mappings[file_ext]
            self.conversion_combo.addItems(available_conversions)
            self.log_text.append(f"已为 {file_ext} 格式加载 {len(available_conversions)} 个转换选项")
        else:
            # 如果格式不在映射中，显示所有选项
            self.conversion_combo.addItems(self.all_conversion_types)
            self.log_text.append(f"未知格式 {file_ext}，显示所有转换选项")
            
    def generate_output_filename(self, input_file_path, conversion_type):
        """根据转换类型和当前时间生成输出文件名"""
        if not input_file_path or not conversion_type:
            return ""
            
        # 获取输入文件的基本信息
        input_path = Path(input_file_path)
        base_name = input_path.stem
        input_dir = input_path.parent
        
        # 获取输出扩展名
        output_ext = self.output_extensions.get(conversion_type, ".out")
        
        # 生成时间戳
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        
        # 生成输出文件名：原文件名_转换类型_时间戳.扩展名
        conversion_short = conversion_type.split(" → ")[1].replace("/", "_")
        output_filename = f"{base_name}_{conversion_short}_{timestamp}{output_ext}"
        
        # 返回完整路径
        return str(input_dir / output_filename)
        
    def select_input_file(self):
        """选择输入文件"""
        file_path, _ = QFileDialog.getOpenFileName(
            self,
            "选择输入文件",
            "",
            "所有支持的文件 (*.doc *.docx *.xls *.xlsx *.ppt *.pptx *.pdf *.txt *.rtf *.epub *.mobi *.azw3 *.html *.md *.jpg *.jpeg *.png *.webp *.gif *.bmp *.tiff *.tif *.raw *.cr2 *.nef *.arw *.dng *.svg *.heic *.mp3 *.wav *.flac *.m4a *.aiff *.aac *.mp4 *.mkv *.avi *.mov *.webm);;"
            "文档文件 (*.doc *.docx *.xls *.xlsx *.ppt *.pptx *.pdf *.txt *.rtf *.epub *.mobi *.azw3 *.html *.md);;"
            "图像文件 (*.jpg *.jpeg *.png *.webp *.gif *.bmp *.tiff *.tif *.raw *.cr2 *.nef *.arw *.dng *.svg *.heic);;"
            "音频文件 (*.mp3 *.wav *.flac *.m4a *.aiff *.aac);;"
            "视频文件 (*.mp4 *.mkv *.avi *.mov *.webm);;"
            "Word文档 (*.doc *.docx);;"
            "Excel文档 (*.xls *.xlsx);;"
            "PowerPoint文档 (*.ppt *.pptx);;"
            "PDF文档 (*.pdf);;"
            "文本文件 (*.txt);;"
            "RTF文档 (*.rtf);;"
            "电子书 (*.epub *.mobi *.azw3);;"
            "网页文件 (*.html);;"
            "Markdown文件 (*.md);;"
            "JPEG图像 (*.jpg *.jpeg);;"
            "PNG图像 (*.png);;"
            "WEBP图像 (*.webp);;"
            "GIF图像 (*.gif);;"
            "BMP图像 (*.bmp);;"
            "TIFF图像 (*.tiff *.tif);;"
            "RAW图像 (*.raw *.cr2 *.nef *.arw *.dng);;"
            "SVG矢量图 (*.svg);;"
            "HEIC图像 (*.heic);;"
            "MP3音频 (*.mp3);;"
            "WAV音频 (*.wav);;"
            "FLAC音频 (*.flac);;"
            "ALAC音频 (*.m4a);;"
            "AIFF音频 (*.aiff);;"
            "AAC音频 (*.aac);;"
            "MP4视频 (*.mp4);;"
            "MKV视频 (*.mkv);;"
            "AVI视频 (*.avi);;"
            "MOV视频 (*.mov);;"
            "WebM视频 (*.webm);;"
            "所有文件 (*.*)"
        )
        
        if file_path:
            self.input_file = file_path
            self.input_file_label.setText(Path(file_path).name)
            self.log_text.append(f"已选择输入文件: {file_path}")
            
            # 根据输入文件格式更新转换选项
            self.update_conversion_options(file_path)
            
            # 检查是否为媒体文件，启用预览按钮
            self.update_preview_button(file_path)
            
            self.check_ready_to_convert()
            
    def select_output_file(self):
        """选择输出目录并自动生成文件名"""
        if not self.input_file:
            QMessageBox.warning(self, "警告", "请先选择输入文件！")
            return
            
        # 获取当前选择的转换类型
        conversion_type = self.conversion_combo.currentText()
        if not conversion_type:
            QMessageBox.warning(self, "警告", "请先选择转换类型！")
            return
        
        # 选择输出目录
        output_dir = QFileDialog.getExistingDirectory(
            self,
            "选择输出目录",
            str(Path(self.input_file).parent)  # 默认为输入文件所在目录
        )
        
        if output_dir:
            # 自动生成输出文件名
            auto_filename = self.generate_output_filename(self.input_file, conversion_type)
            # 将自动生成的文件名放到选择的目录中
            self.output_file = str(Path(output_dir) / Path(auto_filename).name)
            
            self.output_file_label.setText(Path(self.output_file).name)
            self.log_text.append(f"已选择输出目录: {output_dir}")
            self.log_text.append(f"自动生成文件名: {Path(self.output_file).name}")
            self.check_ready_to_convert()
            
    def on_conversion_type_changed(self, conversion_type):
        """转换类型变化处理"""
        # 检查是否为GIF转换
        if conversion_type in ["GIF → PNG", "GIF → WEBP"]:
            self.gif_options_group.setVisible(True)
            self.on_frame_mode_changed(self.frame_mode_combo.currentText())
        else:
            self.gif_options_group.setVisible(False)
        
        # 重新生成输出文件名
        if self.input_file and conversion_type:
            self.select_output_file()
    
    def on_frame_mode_changed(self, mode):
        """帧模式变化处理"""
        conversion_type = self.conversion_combo.currentText()
        
        if mode == "提取单帧":
            self.single_frame_widget.setVisible(True)
        elif mode == "提取所有帧":
            self.single_frame_widget.setVisible(False)
            # 提取所有帧时，输出文件名需要特殊处理
            if self.input_file and conversion_type:
                self.update_output_for_all_frames()
        elif mode == "保持动画":
            self.single_frame_widget.setVisible(False)
            # 只有GIF → WEBP支持保持动画
            if conversion_type == "GIF → PNG":
                self.frame_mode_combo.setCurrentText("提取单帧")
                QMessageBox.information(self, "提示", "PNG格式不支持动画，已切换为提取单帧模式")
    
    def get_gif_frame_info(self):
        """获取GIF帧信息"""
        if not self.input_file:
            QMessageBox.warning(self, "警告", "请先选择GIF文件！")
            return
        
        if not self.input_file.lower().endswith('.gif'):
            QMessageBox.warning(self, "警告", "请选择GIF格式的文件！")
            return
        
        try:
            from converter import FileConverter
            converter = FileConverter()
            frame_info = converter.get_gif_frame_info(self.input_file)
            
            if frame_info:
                frame_count = frame_info['frame_count']
                duration = frame_info.get('duration', 'N/A')
                
                self.frame_spinbox.setMaximum(frame_count - 1)
                info_text = f"总帧数: {frame_count}, 持续时间: {duration}ms/帧"
                self.frame_info_label.setText(info_text)
                self.log_text.append(f"GIF帧信息: {info_text}")
            else:
                self.frame_info_label.setText("无法获取帧信息")
                QMessageBox.warning(self, "错误", "无法获取GIF帧信息")
        except Exception as e:
            self.frame_info_label.setText("获取帧信息失败")
            QMessageBox.critical(self, "错误", f"获取帧信息失败: {str(e)}")
    
    def update_output_for_all_frames(self):
        """为提取所有帧更新输出路径"""
        if not self.input_file:
            return
        
        input_path = Path(self.input_file)
        base_name = input_path.stem
        input_dir = input_path.parent
        
        # 创建输出目录名
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        output_dir_name = f"{base_name}_frames_{timestamp}"
        output_dir = input_dir / output_dir_name
        
        self.output_file = str(output_dir)
        self.output_file_label.setText(f"目录: {output_dir_name}")
        self.log_text.append(f"提取所有帧到目录: {output_dir}")
    
    def check_ready_to_convert(self):
        """检查是否准备好进行转换"""
        if self.input_file and self.output_file and self.conversion_combo.currentText():
            self.convert_btn.setEnabled(True)
            self.convert_btn.setStyleSheet("""
                QPushButton {
                    background-color: #4CAF50;
                    color: white;
                    border: none;
                    padding: 10px;
                    border-radius: 5px;
                    font-weight: bold;
                }
                QPushButton:hover {
                    background-color: #45a049;
                }
            """)
        else:
            self.convert_btn.setEnabled(False)
            self.convert_btn.setStyleSheet("""
                QPushButton {
                    background-color: #cccccc;
                    color: #666666;
                    border: none;
                    padding: 10px;
                    border-radius: 5px;
                    font-weight: bold;
                }
            """)
            
    def start_conversion(self):
        """开始转换"""
        if not self.input_file or not self.output_file:
            QMessageBox.warning(self, "警告", "请先选择输入文件和输出路径！")
            return
            
        conversion_type = self.conversion_combo.currentText()
        
        # 准备转换参数
        conversion_params = {}
        
        # 处理GIF转换参数
        if conversion_type in ["GIF → PNG", "GIF → WEBP"] and self.gif_options_group.isVisible():
            frame_mode = self.frame_mode_combo.currentText()
            
            if frame_mode == "提取单帧":
                if conversion_type == "GIF → PNG":
                    conversion_params['frame_index'] = self.frame_spinbox.value()
                elif conversion_type == "GIF → WEBP":
                    conversion_params['extract_frame'] = self.frame_spinbox.value()
            elif frame_mode == "提取所有帧":
                # 使用特殊的转换类型来处理提取所有帧
                conversion_type = "GIF_EXTRACT_ALL_FRAMES"
                conversion_params['output_format'] = 'PNG' if "PNG" in self.conversion_combo.currentText() else 'JPG'
            elif frame_mode == "保持动画" and conversion_type == "GIF → WEBP":
                # 保持动画，不设置extract_frame参数
                pass
        
        self.log_text.append(f"开始转换: {conversion_type}")
        self.log_text.append(f"输入: {self.input_file}")
        self.log_text.append(f"输出: {self.output_file}")
        if conversion_params:
            self.log_text.append(f"参数: {conversion_params}")
        
        # 禁用转换按钮，显示进度条
        self.convert_btn.setEnabled(False)
        self.progress_bar.setVisible(True)
        self.progress_bar.setValue(0)
        
        # 启动转换线程
        self.conversion_thread = ConversionThread(
            self.input_file, 
            self.output_file, 
            conversion_type,
            conversion_params
        )
        self.conversion_thread.progress_updated.connect(self.update_progress)
        self.conversion_thread.conversion_finished.connect(self.conversion_finished)
        self.conversion_thread.start()
        
        self.statusBar().showMessage("正在转换...")
        
    def update_progress(self, value):
        """更新进度条"""
        self.progress_bar.setValue(value)
        
    def conversion_finished(self, success, message):
        """转换完成处理"""
        self.progress_bar.setVisible(False)
        self.convert_btn.setEnabled(True)
        
        if success:
            self.log_text.append("✓ " + message)
            self.statusBar().showMessage("转换完成")
            QMessageBox.information(self, "成功", message)
        else:
            self.log_text.append("✗ " + message)
            self.statusBar().showMessage("转换失败")
            QMessageBox.critical(self, "错误", message)
            
        # 清理线程
        if self.conversion_thread:
            self.conversion_thread.quit()
            self.conversion_thread.wait()
            self.conversion_thread = None
    
    def update_preview_button(self, file_path):
        """更新预览按钮状态"""
        if not file_path:
            self.preview_btn.setEnabled(False)
            return
        
        # 检查是否为支持预览的媒体文件
        file_ext = Path(file_path).suffix.lower()
        media_extensions = {
            # 视频格式
            '.mp4', '.mkv', '.avi', '.mov', '.webm', '.flv', '.wmv',
            # 音频格式
            '.mp3', '.wav', '.flac', '.aac', '.m4a', '.ogg', '.wma'
        }
        
        is_media_file = file_ext in media_extensions
        self.preview_btn.setEnabled(is_media_file)
        
        if is_media_file:
            self.log_text.append(f"检测到媒体文件，可使用预览编辑功能")
    
    def open_preview_editor(self):
        """打开预览编辑器"""
        if not self.input_file:
            QMessageBox.warning(self, "警告", "请先选择输入文件！")
            return
        
        try:
            from media_preview import MediaPreviewDialog
            
            # 创建并显示预览编辑对话框
            preview_dialog = MediaPreviewDialog(self.input_file, self)
            preview_dialog.exec()
            
        except ImportError as e:
            QMessageBox.critical(self, "错误", f"无法加载预览编辑模块: {str(e)}")
        except Exception as e:
            QMessageBox.critical(self, "错误", f"打开预览编辑器失败: {str(e)}")
            self.log_text.append(f"预览编辑器错误: {str(e)}")
    
    def on_mode_changed(self):
        """转换模式切换处理"""
        if self.single_mode_radio.isChecked():
            # 切换到单文件模式
            self.single_file_widget.setVisible(True)
            self.batch_file_widget.setVisible(False)
            self.convert_btn.setText("开始转换")
            self.check_ready_to_convert()
        else:
            # 切换到批量模式
            self.single_file_widget.setVisible(False)
            self.batch_file_widget.setVisible(True)
            self.convert_btn.setText("开始批量转换")
            self.check_batch_ready_to_convert()
    
    def select_batch_files(self):
        """选择批量文件"""
        file_paths, _ = QFileDialog.getOpenFileNames(
            self,
            "选择要转换的文件",
            "",
            "所有支持的文件 (*.doc *.docx *.xls *.xlsx *.ppt *.pptx *.pdf *.txt *.rtf *.epub *.mobi *.azw3 *.html *.md *.jpg *.jpeg *.png *.webp *.gif *.bmp *.tiff *.tif *.raw *.cr2 *.nef *.arw *.dng *.svg *.heic *.mp3 *.wav *.flac *.m4a *.aiff *.aac *.mp4 *.mkv *.avi *.mov *.webm);;"
            "文档文件 (*.doc *.docx *.xls *.xlsx *.ppt *.pptx *.pdf *.txt *.rtf *.epub *.mobi *.azw3 *.html *.md);;"
            "图像文件 (*.jpg *.jpeg *.png *.webp *.gif *.bmp *.tiff *.tif *.raw *.cr2 *.nef *.arw *.dng *.svg *.heic);;"
            "音频文件 (*.mp3 *.wav *.flac *.m4a *.aiff *.aac);;"
            "视频文件 (*.mp4 *.mkv *.avi *.mov *.webm);;"
            "所有文件 (*.*)"
        )
        
        if file_paths:
            # 添加到批量文件列表
            for file_path in file_paths:
                if file_path not in self.batch_file_list:
                    self.batch_file_list.append(file_path)
                    self.batch_files_list.addItem(Path(file_path).name)
            
            # 更新显示
            file_count = len(self.batch_file_list)
            self.batch_files_label.setText(f"已选择 {file_count} 个文件")
            self.log_text.append(f"添加了 {len(file_paths)} 个文件到批量转换列表")
            
            # 根据选择的文件更新转换选项
            self.update_batch_conversion_options()
            
            self.check_batch_ready_to_convert()
    
    def update_batch_conversion_options(self):
        """根据批量选择的文件更新转换选项"""
        if not hasattr(self, 'batch_file_list') or not self.batch_file_list:
            return
        
        # 获取所有文件的扩展名
        file_extensions = set()
        for file_path in self.batch_file_list:
            file_ext = Path(file_path).suffix.lower()
            file_extensions.add(file_ext)
        
        # 找出所有文件类型的共同转换选项
        common_conversions = None
        supported_extensions = []
        
        for file_ext in file_extensions:
            if file_ext in self.format_mappings:
                supported_extensions.append(file_ext)
                available_conversions = set(self.format_mappings[file_ext])
                
                if common_conversions is None:
                    common_conversions = available_conversions
                else:
                    # 取交集，找出共同的转换选项
                    common_conversions = common_conversions.intersection(available_conversions)
        
        # 更新转换选项下拉菜单
        self.conversion_combo.clear()
        
        if common_conversions:
            # 如果有共同的转换选项，只显示这些选项
            sorted_conversions = sorted(list(common_conversions))
            self.conversion_combo.addItems(sorted_conversions)
            self.log_text.append(f"已为选择的文件类型 {list(file_extensions)} 加载 {len(sorted_conversions)} 个共同转换选项")
        elif supported_extensions:
            # 如果没有共同选项但有支持的格式，显示所有相关选项
            all_available_conversions = set()
            for file_ext in supported_extensions:
                all_available_conversions.update(self.format_mappings[file_ext])
            
            sorted_conversions = sorted(list(all_available_conversions))
            self.conversion_combo.addItems(sorted_conversions)
            self.log_text.append(f"已为选择的文件类型 {list(file_extensions)} 加载 {len(sorted_conversions)} 个可用转换选项")
        else:
            # 如果都不支持，显示所有选项
            self.conversion_combo.addItems(self.all_conversion_types)
            self.log_text.append(f"选择的文件类型 {list(file_extensions)} 中包含未知格式，显示所有转换选项")
    
    def clear_batch_files(self):
        """清空批量文件列表"""
        self.batch_file_list.clear()
        self.batch_files_list.clear()
        self.batch_files_label.setText("未选择文件")
        self.log_text.append("已清空批量文件列表")
        
        # 重置转换选项为所有选项
        self.conversion_combo.clear()
        self.conversion_combo.addItems(self.all_conversion_types)
        
        self.check_batch_ready_to_convert()
    
    def select_batch_output_dir(self):
        """选择批量转换输出目录"""
        output_dir = QFileDialog.getExistingDirectory(
            self,
            "选择批量转换输出目录",
            ""
        )
        
        if output_dir:
            self.batch_output_dir = output_dir
            self.batch_output_label.setText(Path(output_dir).name)
            self.log_text.append(f"已选择批量输出目录: {output_dir}")
            self.check_batch_ready_to_convert()
    
    def check_batch_ready_to_convert(self):
        """检查批量转换是否准备就绪"""
        if (hasattr(self, 'batch_file_list') and self.batch_file_list and 
            hasattr(self, 'batch_output_dir') and self.batch_output_dir and 
            self.conversion_combo.currentText()):
            self.convert_btn.setEnabled(True)
            self.convert_btn.setStyleSheet("""
                QPushButton {
                    background-color: #4CAF50;
                    color: white;
                    border: none;
                    padding: 10px;
                    border-radius: 5px;
                    font-weight: bold;
                }
                QPushButton:hover {
                    background-color: #45a049;
                }
            """)
        else:
            self.convert_btn.setEnabled(False)
            self.convert_btn.setStyleSheet("""
                QPushButton {
                    background-color: #cccccc;
                    color: #666666;
                    border: none;
                    padding: 10px;
                    border-radius: 5px;
                    font-weight: bold;
                }
            """)
    
    def start_conversion(self):
        """开始转换（单文件或批量）"""
        if self.single_mode_radio.isChecked():
            self.start_single_conversion()
        else:
            self.start_batch_conversion()
    
    def start_single_conversion(self):
        """开始单文件转换"""
        if not self.input_file or not self.output_file:
            QMessageBox.warning(self, "警告", "请先选择输入文件和输出路径！")
            return
            
        conversion_type = self.conversion_combo.currentText()
        
        # 准备转换参数
        conversion_params = {}
        
        # 处理GIF转换参数
        if conversion_type in ["GIF → PNG", "GIF → WEBP"] and self.gif_options_group.isVisible():
            frame_mode = self.frame_mode_combo.currentText()
            
            if frame_mode == "提取单帧":
                if conversion_type == "GIF → PNG":
                    conversion_params['frame_index'] = self.frame_spinbox.value()
                elif conversion_type == "GIF → WEBP":
                    conversion_params['extract_frame'] = self.frame_spinbox.value()
            elif frame_mode == "提取所有帧":
                # 使用特殊的转换类型来处理提取所有帧
                conversion_type = "GIF_EXTRACT_ALL_FRAMES"
                conversion_params['output_format'] = 'PNG' if "PNG" in self.conversion_combo.currentText() else 'JPG'
            elif frame_mode == "保持动画" and conversion_type == "GIF → WEBP":
                # 保持动画，不设置extract_frame参数
                pass
        
        self.log_text.append(f"开始转换: {conversion_type}")
        self.log_text.append(f"输入: {self.input_file}")
        self.log_text.append(f"输出: {self.output_file}")
        if conversion_params:
            self.log_text.append(f"参数: {conversion_params}")
        
        # 禁用转换按钮，显示进度条
        self.convert_btn.setEnabled(False)
        self.cancel_btn.setEnabled(True)
        self.progress_group.setVisible(True)
        self.progress_bar.setVisible(True)
        self.progress_bar.setValue(0)
        
        # 启动转换线程
        self.conversion_thread = ConversionThread(
            self.input_file, 
            self.output_file, 
            conversion_type,
            conversion_params
        )
        self.conversion_thread.progress_updated.connect(self.update_progress)
        self.conversion_thread.conversion_finished.connect(self.single_conversion_finished)
        self.conversion_thread.start()
        
        self.statusBar().showMessage("正在转换...")
    
    def start_batch_conversion(self):
        """开始批量转换"""
        if not hasattr(self, 'batch_file_list') or not self.batch_file_list:
            QMessageBox.warning(self, "警告", "请先选择要转换的文件！")
            return
        
        if not hasattr(self, 'batch_output_dir') or not self.batch_output_dir:
            QMessageBox.warning(self, "警告", "请先选择输出目录！")
            return
        
        conversion_type = self.conversion_combo.currentText()
        if not conversion_type:
            QMessageBox.warning(self, "警告", "请先选择转换类型！")
            return
        
        self.log_text.append(f"开始批量转换: {conversion_type}")
        self.log_text.append(f"文件数量: {len(self.batch_file_list)}")
        self.log_text.append(f"输出目录: {self.batch_output_dir}")
        
        # 禁用转换按钮，启用取消按钮
        self.convert_btn.setEnabled(False)
        self.cancel_btn.setEnabled(True)
        
        # 显示进度界面
        self.progress_group.setVisible(True)
        self.progress_bar.setVisible(True)
        self.current_file_label.setVisible(True)
        self.batch_progress_list.setVisible(True)
        self.progress_bar.setValue(0)
        
        # 清空进度列表
        self.batch_progress_list.clear()
        
        # 启动批量转换线程
        self.batch_conversion_thread = BatchConversionThread(
            self.batch_file_list,
            self.batch_output_dir,
            conversion_type
        )
        
        # 连接信号
        self.batch_conversion_thread.progress_updated.connect(self.update_progress)
        self.batch_conversion_thread.file_progress_updated.connect(self.update_file_progress)
        self.batch_conversion_thread.current_file_changed.connect(self.update_current_file)
        self.batch_conversion_thread.conversion_finished.connect(self.batch_conversion_finished)
        
        self.batch_conversion_thread.start()
        self.statusBar().showMessage("正在批量转换...")
    
    def cancel_conversion(self):
        """取消转换"""
        if self.single_mode_radio.isChecked() and self.conversion_thread:
            # 取消单文件转换
            self.conversion_thread.terminate()
            self.conversion_thread.wait()
            self.conversion_thread = None
            self.single_conversion_finished(False, "转换已取消")
        elif self.batch_conversion_thread:
            # 取消批量转换
            self.batch_conversion_thread.cancel()
            self.log_text.append("正在取消批量转换...")
    
    def update_current_file(self, filename):
        """更新当前处理的文件"""
        self.current_file_label.setText(f"正在处理: {filename}")
    
    def update_file_progress(self, filename, progress):
        """更新单个文件的进度"""
        # 在列表中显示文件进度
        if progress == 100:
            status = "✓ 完成"
            color = "green"
        elif progress == -1:
            status = "✗ 失败"
            color = "red"
        else:
            status = f"{progress}%"
            color = "blue"
        
        item_text = f"{filename} - {status}"
        
        # 查找是否已存在该文件的项目
        found = False
        for i in range(self.batch_progress_list.count()):
            item = self.batch_progress_list.item(i)
            if item.text().startswith(filename):
                item.setText(item_text)
                item.setForeground(QColor(color))
                found = True
                break
        
        if not found:
            # 添加新项目
            item = QListWidgetItem(item_text)
            item.setForeground(QColor(color))
            self.batch_progress_list.addItem(item)
        
        # 滚动到最新项目
        self.batch_progress_list.scrollToBottom()
    
    def single_conversion_finished(self, success, message):
        """单文件转换完成处理"""
        self.progress_group.setVisible(False)
        self.convert_btn.setEnabled(True)
        self.cancel_btn.setEnabled(False)
        
        if success:
            self.log_text.append("✓ " + message)
            self.statusBar().showMessage("转换完成")
            QMessageBox.information(self, "成功", message)
        else:
            self.log_text.append("✗ " + message)
            self.statusBar().showMessage("转换失败")
            QMessageBox.critical(self, "错误", message)
            
        # 清理线程
        if self.conversion_thread:
            self.conversion_thread.quit()
            self.conversion_thread.wait()
            self.conversion_thread = None
    
    def batch_conversion_finished(self, success, message, result_stats):
        """批量转换完成处理"""
        self.convert_btn.setEnabled(True)
        self.cancel_btn.setEnabled(False)
        self.current_file_label.setVisible(False)
        
        # 显示结果统计
        total = result_stats.get('total', 0)
        success_count = result_stats.get('success', 0)
        failed_count = result_stats.get('failed', 0)
        failed_files = result_stats.get('failed_files', [])
        
        self.log_text.append("=== 批量转换完成 ===")
        self.log_text.append(f"总文件数: {total}")
        self.log_text.append(f"成功: {success_count}")
        self.log_text.append(f"失败: {failed_count}")
        
        if failed_files:
            self.log_text.append("失败文件:")
            for failed_file in failed_files:
                self.log_text.append(f"  - {failed_file}")
        
        self.statusBar().showMessage("批量转换完成")
        
        # 显示结果对话框
        if failed_count == 0:
            QMessageBox.information(self, "批量转换完成", 
                                   f"所有文件转换成功！\n\n总计: {total} 个文件")
        else:
            detail_msg = f"总计: {total} 个文件\n成功: {success_count} 个\n失败: {failed_count} 个"
            if failed_files:
                detail_msg += "\n\n失败文件:\n" + "\n".join(failed_files[:5])
                if len(failed_files) > 5:
                    detail_msg += f"\n... 还有 {len(failed_files) - 5} 个文件"
            
            QMessageBox.warning(self, "批量转换完成", detail_msg)
        
        # 清理线程
        if self.batch_conversion_thread:
            self.batch_conversion_thread.quit()
            self.batch_conversion_thread.wait()
            self.batch_conversion_thread = None


def main():
    """主函数"""
    app = QApplication(sys.argv)
    
    # 设置应用程序信息
    app.setApplicationName("文件格式转换工具")
    app.setApplicationVersion("1.0")
    
    # 创建主窗口
    window = FileFormatConverter()
    window.show()
    
    # 运行应用程序
    sys.exit(app.exec())


if __name__ == "__main__":
    main()